package com.ys.service.amazonorder.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bo.vo.R;
import com.ys.dto.AddDto;
import com.ys.dto.DtreeSqlDto;
import com.ys.dto.EditDto;
import com.ys.dto.YsTreeDto;
import com.ys.entity.amazonorder.TbBaseinfoLmwh;
import com.ys.mapper.amazonorder.TbBaseinfoLmwhMapper;
import com.ys.mapper.business.BusinessMapper;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.service.amazonorder.TbBaseinfoLmwhService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.dhecp.StringUtils;
import com.ys.vo.LayuiTableVoJA;

@Service("tbBaseinfoLmwhService")
public class TbBaseinfoLmwhServiceImpl implements TbBaseinfoLmwhService {
	
	@Autowired
	private TbBaseinfoLmwhMapper tbBaseinfoLmwhMapper;
	@Autowired
	private DiySqlMapper diySqlMapper;

	@Autowired
    private BusinessMapper businessMapper;

	@Autowired
    private CommonApiService<TbBaseinfoLmwh> commonApiService;
	@Override
	public R add(Map<String, Object> params) {
        TbBaseinfoLmwh entity = JSON.parseObject(JSON.toJSONString(params), TbBaseinfoLmwh.class);


        if (entity.getPid() == null) {
            return R.error("上级ID不能为空");
        }
        TbBaseinfoLmwh tbBaseinfoLmwh = new TbBaseinfoLmwh().setId(entity.getPid()).queryFirst();
        if (tbBaseinfoLmwh == null) {
            return R.error("上级不存在");
        }

        if (entity.getName() == null || entity.getName().length() == 0) {
            return R.error("类目名称不能为空");
        }else if (entity.getName().length() > 100) {
            return R.error("类目名称长度不能大于100个字符!");
        }

        Long pNodeRgt = tbBaseinfoLmwh.getNodeRgt();
        businessMapper.updateLmgNodeLftAddTwo(pNodeRgt);
        businessMapper.updateLmNodeRgtAddTwo(pNodeRgt);

        Long nodeLft = tbBaseinfoLmwh.getNodeRgt();
        Long nodeRgt = tbBaseinfoLmwh.getNodeRgt() + 1;
        Integer floor = tbBaseinfoLmwh.getFloor() + 1;
        entity.setNodeLft(nodeLft);
        entity.setNodeRgt(nodeRgt);
        entity.setFloor(floor);

		tbBaseinfoLmwhMapper.insert(entity);

        //查询所有数据
        List<Map<String, Object>> tbBaseinfoLmwhList1 = new TbBaseinfoLmwh()
                .addLeftJoin("TB_BaseinfoLmwh t2 on A.Pid = t2.Id AND t2.Floor != 0")
                .addField("t2.name as pidName")
                .where("A.Floor != 0")
                .setOrderby("A.Id asc")
                .queryMap();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id",entity.getId());
        jsonObject.put("name",entity.getName());
        StringBuilder stringBuilder = queryParentIds(jsonObject, tbBaseinfoLmwhList1);

        String categoryPath = stringBuilder.toString();
        if (entity.getFloor() == 1) {
            categoryPath = String.valueOf(stringBuilder.append(entity.getName()));
        }
        entity.setCategoryPath(categoryPath);
        tbBaseinfoLmwhMapper.update(entity);
		return R.ok(AddDto.closeAndReload());
	}
	
	@Override
	public R edit(Map<String, Object> params) {


		TbBaseinfoLmwh entity = JSON.parseObject(JSON.toJSONString(params), TbBaseinfoLmwh.class);
        TbBaseinfoLmwh tbBaseinfoLmwh = new TbBaseinfoLmwh().setId(entity.getId()).queryFirst();
        if (tbBaseinfoLmwh == null){
            R.error("该商品类目不存在!");
        }else if (entity.getName().length() > 100) {
            return R.error("类目名称长度不能大于100个字符!");
        }
        //查询所有数据
        List<Map<String, Object>> tbBaseinfoLmwhList1 = new TbBaseinfoLmwh()
                .addLeftJoin("TB_BaseinfoLmwh t2 on A.Pid = t2.Id AND t2.Floor != 0")
                .addField("t2.name as pidName")
                .where("A.Floor != 0")
                .setOrderby("A.Id asc")
                .queryMap();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id",entity.getId());
        jsonObject.put("name",entity.getName());
        StringBuilder stringBuilder = queryParentIds(jsonObject, tbBaseinfoLmwhList1);

        String categoryPath = stringBuilder.toString();
        if (tbBaseinfoLmwh.getFloor() == 1) {
            categoryPath = String.valueOf(stringBuilder.append(entity.getName()));
        }
        entity.setCategoryPath(categoryPath);
		tbBaseinfoLmwhMapper.update(entity);
		


		return R.ok(EditDto.closeAndReload());
	}

	/**
	 * 删除
	 */
	@Override
    public R deleteTbBaseinfoLmwh(Long id) {
		
        if (new TbBaseinfoLmwh().setId(id).count() == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("商品类目不存在,删除失败!");
        }
        if (new TbBaseinfoLmwh().setPid(id).count() != 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("商品类目有子类目,不允许删除!");
        }

        diySqlMapper.deleteTbBaseinfoLmwh(id);

		return R.ok();
	
	}
    @Override
    public DtreeSqlDto dtree() {

        DtreeSqlDto.StatusDto status = DtreeSqlDto.StatusDto.init(200, "");

        List<DtreeSqlDto.DataDto> data = new ArrayList<DtreeSqlDto.DataDto>();
        List<TbBaseinfoLmwh> tbBaseinfoLmwhList = new TbBaseinfoLmwh()
                .setOrderby("A.Id asc")
                .queryList();
        // 处理部门数据，方便遍历
        Map<Long, List<TbBaseinfoLmwh>> MAP_PGUID_LIST = new HashMap<Long, List<TbBaseinfoLmwh>>();
        for(TbBaseinfoLmwh tbBaseinfoLmwh : tbBaseinfoLmwhList) {
            List<TbBaseinfoLmwh> listValue = MAP_PGUID_LIST.containsKey(tbBaseinfoLmwh.getPid()) ? MAP_PGUID_LIST.get(tbBaseinfoLmwh.getPid()) : new ArrayList<TbBaseinfoLmwh>();
            listValue.add(tbBaseinfoLmwh);
            MAP_PGUID_LIST.put(tbBaseinfoLmwh.getPid(), listValue);
        }

        // 一级菜单
        {
            TbBaseinfoLmwh tbBaseinfoLmwhRoot = new TbBaseinfoLmwh().setFloor(0).queryFirst();
            String id = tbBaseinfoLmwhRoot.getId().toString();
            String title = tbBaseinfoLmwhRoot.getName();
            String parentId = tbBaseinfoLmwhRoot.getPid().toString();

            // 二级菜单
            List<DtreeSqlDto.DataDto> children = getChildren(tbBaseinfoLmwhRoot, MAP_PGUID_LIST);

            DtreeSqlDto.DataDto dataDto1 = new DtreeSqlDto.DataDto(id, title, parentId, DtreeSqlDto.DataDto.initCheckArr(null), children);
            data.add(dataDto1);
        }
        return new DtreeSqlDto(status, data);
    }

    private List<DtreeSqlDto.DataDto> getChildren(TbBaseinfoLmwh current, Map<Long, List<TbBaseinfoLmwh>> MAP_PGUID_LIST) {

        List<TbBaseinfoLmwh> tbBaseinfoLmwhList = MAP_PGUID_LIST.get(current.getId());
        List<DtreeSqlDto.DataDto> children = new ArrayList<DtreeSqlDto.DataDto>();
        if (tbBaseinfoLmwhList == null) {
            return null;
        } else {
            for(TbBaseinfoLmwh tbBaseinfoLmwh : tbBaseinfoLmwhList) {
                String id = String.valueOf(tbBaseinfoLmwh.getId());
                String title = tbBaseinfoLmwh.getName();
                String parentId = String.valueOf(tbBaseinfoLmwh.getPid());

                List<DtreeSqlDto.DataDto> childrenSub = getChildren(tbBaseinfoLmwh, MAP_PGUID_LIST);
                DtreeSqlDto.DataDto dataDtoSub = new DtreeSqlDto.DataDto(id, title, parentId, DtreeSqlDto.DataDto.initCheckArr(null), childrenSub);
                children.add(dataDtoSub);
            }
        }

        return children;
    }

	@Override
	public YsTreeDto ysTree() {
		List<YsTreeDto.DataDto> data = new ArrayList<YsTreeDto.DataDto>();
        List<TbBaseinfoLmwh> tbBaseinfoLmwhList = new TbBaseinfoLmwh()
                .setOrderby("A.Id asc")
                .queryList();
        // 处理部门数据，方便遍历
        Map<Long, List<TbBaseinfoLmwh>> MAP_PGUID_LIST = new HashMap<Long, List<TbBaseinfoLmwh>>();
        for(TbBaseinfoLmwh tbBaseinfoLmwh : tbBaseinfoLmwhList) {
            List<TbBaseinfoLmwh> listValue = MAP_PGUID_LIST.containsKey(tbBaseinfoLmwh.getPid()) ? MAP_PGUID_LIST.get(tbBaseinfoLmwh.getPid()) : new ArrayList<TbBaseinfoLmwh>();
            listValue.add(tbBaseinfoLmwh);
            MAP_PGUID_LIST.put(tbBaseinfoLmwh.getPid(), listValue);
        }

        // 一级菜单
        {
            TbBaseinfoLmwh tbBaseinfoLmwhRoot = new TbBaseinfoLmwh().setFloor(0).queryFirst();
            String id = tbBaseinfoLmwhRoot.getId().toString();
            String title = tbBaseinfoLmwhRoot.getName();

            // 二级菜单
            List<YsTreeDto.DataDto> children = getYsTreeSub(tbBaseinfoLmwhRoot, MAP_PGUID_LIST);

            YsTreeDto.DataDto dataDto1 = new YsTreeDto.DataDto(id, title, children);
            data.add(dataDto1);
        }

		return new YsTreeDto(data);
	}
	
	private List<YsTreeDto.DataDto> getYsTreeSub(TbBaseinfoLmwh current, Map<Long, List<TbBaseinfoLmwh>> MAP_PGUID_LIST) {

        List<TbBaseinfoLmwh> tbBaseinfoLmwhList = MAP_PGUID_LIST.get(current.getId());
        List<YsTreeDto.DataDto> children = new ArrayList<YsTreeDto.DataDto>();
        if (tbBaseinfoLmwhList == null) {
            return null;
        } else {
            for(TbBaseinfoLmwh tbBaseinfoLmwh : tbBaseinfoLmwhList) {
                String id = String.valueOf(tbBaseinfoLmwh.getId());
                String title = tbBaseinfoLmwh.getName();

                List<YsTreeDto.DataDto> childrenSub = getYsTreeSub(tbBaseinfoLmwh, MAP_PGUID_LIST);
                YsTreeDto.DataDto dataDtoSub = new YsTreeDto.DataDto(id, title, childrenSub);
                children.add(dataDtoSub);
            }
        }
		
		return children;
	}

    /**
     * 查询父级的所有路径
     * @param entity
     * @return
     */
    @Override
    public LayuiTableVoJA searchLay(TbBaseinfoLmwh entity) {
        //查询分页数据
        entity.setOrderby("A.CreateTime ASC");
        entity.where("A.Floor != 0 AND A.Status = 1");
        LayuiTableVoJA tableVoJA = commonApiService.searchLay(entity);
        return tableVoJA;
    }


    /**
     * 递归遍历获取指定菜单的所有父节点
     *
     * @param trees        当前菜单
     * @param jsonObject 子菜单信息
     */
    public StringBuilder queryParentIds(JSONObject jsonObject,  List<Map<String, Object>> trees) {
        //递归获取父级ids,不包含自己
        List<String> parentNames = new ArrayList<>();
        StringBuilder parentLj = new StringBuilder();
        this.treeOrgParent(trees, Long.valueOf(jsonObject.get("id").toString()), parentNames);

        // 倒序List
        Collections.reverse(parentNames);

        for (int i = 0; i < parentNames.size(); i++) {
            if (i == 0){
                parentLj.append(parentNames.get(i));
            }else {
                parentLj.append(">" + parentNames.get(i));
            }
        }
        if (parentNames.size() != 0){
            parentLj.append(">" + jsonObject.get("name").toString());
        }
        return parentLj;
    }

    /**
     * 递归获取父级ids
     * @param trees 所有类目信息
     * @param treeId 类目id
     * @param parentNames 类目父级名称所有
     */
    public void treeOrgParent( List<Map<String, Object>> trees, Long treeId, List<String> parentNames) {
        for (Map<String, Object> tree : trees) {
            //判断是否有父节点
            if (StringUtils.isEmpty(tree.get("pid")) || tree.get("floor").equals(1)) {
                continue;
            }

            if (treeId.equals(tree.get("id"))) {
                parentNames.add(tree.get("pidName").toString());
                treeOrgParent(trees, Long.valueOf(tree.get("pid").toString()), parentNames);
            }
        }
    }

}
